/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.manuscripts.analysis;

import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.dom4j.DocumentException;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class Main {

    /**
     * výstup je vhodné uložit do souboru a ten pak seřadit pomocí
     * grep -n -r
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        String[] testArgs = new String[]{
            "-dir", "/home/rehan/rukopisy/ENRICH",
            "-xslt", "/home/rehan/NetBeansProjects/Rukopisy-analysis/src/cz/mzk/manuscripts/analysis/locusPaths.xsl"
        };
        //args = testArgs;
        try {
            CommandLine cmd = initCommandLine(args);
            File rootDir = new File(cmd.getOptionValue("dir"));
            List<File> teiFiles = findTeiFiles(rootDir, true);
            File xpath = new File(cmd.getOptionValue("xslt"));
            LocusPathsAnalyzer analyzer = new LocusPathsAnalyzer(xpath);
            for (File teiFile : teiFiles) {
//                System.out.println("file: " + teiFile.getAbsolutePath());
                analyzer.addTeiFile(teiFile);
            }
            LocusPathsStatistics statistics = analyzer.analyze();
            System.out.println(statistics);
        } catch (ParseException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (DocumentException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static CommandLine initCommandLine(String[] args) throws ParseException {
        Options options = new Options();
        Option dir = new Option("dir", true, "Directory with tei files");
        dir.setRequired(true);
        options.addOption(dir);

        Option xslt = new Option("xslt", true, "Path to xslt that transforms tei to locus paths");
        xslt.setRequired(true);
        options.addOption(xslt);

        CommandLineParser parser = new PosixParser();
        return parser.parse(options, args);
    }

    private static List<File> findTeiFiles(File rootDir, boolean searchInSubdirs) {
        List<File> result = new ArrayList<File>();
        addTeiFilesToList(result, rootDir, searchInSubdirs);
        return result;
    }

    private static void addTeiFilesToList(List<File> list, File dir, boolean searchInSubdirs) {
        File[] teiFilesInDir = findTeiFiles(dir);
        list.addAll(Arrays.asList(teiFilesInDir));
        if (searchInSubdirs) {
            File[] subdirs = findSubdirs(dir);
            for (File subDir : subdirs) {
                addTeiFilesToList(list, subDir, searchInSubdirs);
            }
        }
    }

    private static File[] findTeiFiles(File rootDir) {
        return rootDir.listFiles(new FilenameFilter() {

            public boolean accept(File dir, String name) {
                return name.endsWith("tei.xml");
            }
        });
    }

    private static File[] findSubdirs(File rootDir) {
        return rootDir.listFiles(new FileFilter() {

            public boolean accept(File file) {
                return file.isDirectory() && !file.getName().startsWith(".");
            }
        });
    }
}
